package com.example.websocket.controller;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class ChatController {

    private final SimpMessagingTemplate messagingTemplate;

    public ChatController(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    @MessageMapping("/chat.private")
    public void sendPrivateMessage(@Payload String message, SimpMessageHeaderAccessor headerAccessor) {
        String sender = headerAccessor.getUser().getName();
        String recipient = headerAccessor.getFirstNativeHeader("recipient");
        
        // 构建消息内容
        String messageContent = String.format("来自 %s 的消息: %s", sender, message);
        
        // 发送给指定用户
        messagingTemplate.convertAndSendToUser(
            recipient,
            "/queue/messages",
            messageContent
        );
    }
} 